import { countEnergy } from "../../role/spawn";
import { Group } from "../group";

export class GroupTerminal extends Group{
    constructor(spawnRoom=undefined){
        super(spawnRoom);
        this.creeps=[];
    }
    get info(){
        if(this._info !== undefined){
            return this._info;
        }
        const ret = super.info;
        ret.size = this.size;
        for(const creep of this.creeps){
            ret.totalCost += countEnergy(creep.body);
            for(const type in creep.store){
                if(!ret.totalResource[type]){
                    ret.totalResource[type] = 0;
                }
                ret.totalResource += creep.store[type];
            }
        }
        return this._info = ret;
    }
    serialize(){
        let creepNames=[];
        for(let i=0; i<this.creepNames.length; i++){
            let name=this.creepNames[i]
            if(!Game.creeps[name]){
                continue;
            }
            creepNames.push(name);
        }
        return {super:super.serialize(), creepNames:creepNames};
    }
    /**
     * 
     * @param {Object} obj 
     * @param {string[]} obj.creepNames
     * @returns 
     */
    deserialize(obj){
        super.deserialize(obj.super);
        this.creepNames=obj.creepNames;
        return this;
    }
    get size(){
        return this.creepNames.length;
    }
    get creeps(){
        let ans=[];
        try{
            for(let creepName of this.creepNames){
                let creep=Game.creeps[creepName];
                if(!creep){
                    continue;
                }
                ans.push(creep);
            }
        }catch(e){
            this.creepNames=[];
        }
        return ans;
    }
    set creeps(creeps){
        this.creepNames=[];
        for(let creep of creeps){
            if(creep==undefined){
                continue;
            }
            this.creepNames.push(creep.name);
        }
    }
    get size(){
        return this.creepNames.length;
    }
    /**
     * 
     * @param {Creep} creep 
     */
    addCreep(creep){
        this.creepNames.push(creep.name);
        return OK;
    }
    /**@param {String} creepName  */
    removeCreep(creepName){
        let index=this.creepNames.findIndex((_value,_index, obj)=>obj==creepName);
        this.creepNames.splice(index,1);
    }
}